//
//  MemberDetailViewController.m
//  StockNetManager
//
//  Created by 小焘无量 on 2023/3/22.
//

#import "MemberDetailViewController.h"
#import "ChoseTimeView.h"


@interface MemberDetailViewController ()

@property (weak, nonatomic) IBOutlet UILabel *phoneLab;
@property (weak, nonatomic) IBOutlet UILabel *registTimeLab;
@property (weak, nonatomic) IBOutlet UILabel *isMemberLab;

@property (weak, nonatomic) IBOutlet UIButton *memberStartBtn;
@property (weak, nonatomic) IBOutlet UIButton *memberEndBtn;

@property (weak, nonatomic) IBOutlet UILabel *regionTimeLab;


@property (weak, nonatomic) IBOutlet UIView *companyBgView;
@property (weak, nonatomic) IBOutlet UITextField *companyNameTF;
@property (weak, nonatomic) IBOutlet UITextField *companyShortNameTF;
@property (weak, nonatomic) IBOutlet UITextField *companyUserTF;
@property (weak, nonatomic) IBOutlet UITextField *companyUserPhoneTF;

@property (weak, nonatomic) IBOutlet UIButton *bottomBtn;

@property (nonatomic, strong) NSDate *startDate;
@property (nonatomic, strong) NSDate *endDate;

@property (nonatomic, strong) UserInfoModel *model;

@end

@implementation MemberDetailViewController

#pragma mark - LifeCycle

-(instancetype)initWithModel:(UserInfoModel *)model {
    if (self = [super init]) {
        self.model = model;
    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self UIConfig];
}

-(void)dealloc {
    //[[NSNotificationCenter defaultCenter] removeObserver:self];
}

#pragma mark - view layout
-(void)UIConfig{
    
    self.phoneLab.text = [NSString stringWithFormat:@"用户手机号：%@", self.model.phone];
    self.registTimeLab.text = [NSString stringWithFormat:@"用户注册日期：%@", self.model.createTime];
    
    if (self.model.level == 0) {
        // 非会员
        [self notMemberConfig:self.model];
        return;
    }
    
    // 会员：
    [self isMemberConfig:self.model];
}


// 非会员界面设置
-(void)notMemberConfig:(UserInfoModel *)model {
    
    self.navigationItem.title = @"开通会员";
    
    self.isMemberLab.text = @"（非会员）";
    [self.memberStartBtn setTitle:@"请选择开通时间" forState:UIControlStateNormal];
    [self.memberEndBtn setTitle:@"请选择结束时间" forState:UIControlStateNormal];
    self.regionTimeLab.hidden = YES;
    
    self.companyBgView.hidden = YES;
    [self.bottomBtn setTitle:@"开通会员" forState:UIControlStateNormal];
    
}

// 会员、且填写公司信息
-(void)isMemberConfig:(UserInfoModel *)model {
    
    self.isMemberLab.text = @"（会员）";
    
    self.navigationItem.title = model.fillCompany ? @"查询结果" : @"填写公司信息";
    
    self.memberStartBtn.userInteractionEnabled = NO;
    self.memberEndBtn.userInteractionEnabled = NO;
    self.regionTimeLab.hidden = NO;
    self.companyBgView.hidden = NO;
    
    [self.memberStartBtn setTitle:model.openingTime forState:UIControlStateNormal];
    [self.memberEndBtn setTitle:model.expirationTime forState:UIControlStateNormal];
    
    //计算到期时间
    self.regionTimeLab.text = [NSString stringWithFormat:@"%@后到期", [self getRemainingTime]];
    
    self.companyNameTF.text = model.company.name;
    self.companyShortNameTF.text = model.company.abbName;
    self.companyUserTF.text = model.company.linkman;
    self.companyUserPhoneTF.text = model.company.phone;
    
    [self.bottomBtn setTitle: @"保存公司信息" forState:UIControlStateNormal];
}

#pragma mark - Event Response

- (IBAction)startMemberBtnAction:(UIButton *)sender {
    
    WeakSelf;
    [ChoseTimeView showMaxDate:self.endDate minDate:[NSDate date] complate:^(NSDate * _Nonnull chosedDate) {
        weakSelf.startDate = chosedDate;
        [weakSelf.memberStartBtn setTitle:[NSString stringFromDate:chosedDate format:@"yyyy-MM-dd"] forState:UIControlStateNormal];
        if (weakSelf.endDate) {
            weakSelf.regionTimeLab.hidden = NO;
            weakSelf.regionTimeLab.text = [NSString stringWithFormat:@"自开始日期起 %@后到期", [weakSelf getRegionTime]];
        }
    }];
    
}

- (IBAction)endMemberBtnAction:(UIButton *)sender {
    
    if (!self.startDate) {
        [MBProgressHUD showMessage:@"请先选择开始时间"];
        return;
    }
    
    WeakSelf;
    [ChoseTimeView showMaxDate:nil minDate:self.startDate complate:^(NSDate * _Nonnull chosedDate) {
        weakSelf.endDate = chosedDate;
        [weakSelf.memberEndBtn setTitle:[NSString stringFromDate:chosedDate format:@"yyyy-MM-dd"] forState:UIControlStateNormal];
        if (weakSelf.startDate) {
            weakSelf.regionTimeLab.hidden = NO;
            weakSelf.regionTimeLab.text = [NSString stringWithFormat:@"自开始日期起 %@后到期", [weakSelf getRegionTime]];
        }
    }];
    
    
}

- (IBAction)openMemberOrEditInfoBtnAction:(UIButton *)sender {
    
    
    
    if (self.model.level == 0) {
        // 开通会员
        [self openMemberAction];
        return;
    }
    
    // 保存公司信息
    [self saveCompanyNetwork];
}


#pragma mark - Delegate,DataSource

#pragma mark - Network

// 开通会员
-(void)openMemberNetwork {
    
    NSInteger startTime = [self.startDate timeIntervalSince1970]*1000;
    NSInteger endTime = [self.endDate timeIntervalSince1970]*1000;
    
    NSMutableDictionary *dic = [[NSMutableDictionary alloc]init];
    [dic setObject:self.model.userId forKey:@"memberId"];// 用户id
    [dic setObject:[NSString stringWithFormat:@"%ld",startTime] forKey:@"startTimeStamp"];// 开始时间戳
    [dic setObject:[NSString stringWithFormat:@"%ld",endTime] forKey:@"endTimeStamp"];// 结束时间戳
    [dic setObject:@"2" forKey:@"type"];// 开通类型 1：指定多少个月 2:指定起止时间
    
    self.bottomBtn.userInteractionEnabled = NO;
    
    WeakSelf;
    [MBProgressHUD showLoadingMessage:nil];
    [[APIManager manager] Post:URL_openMember parameters:dic success:^(id  _Nonnull responseObject) {
        [MBProgressHUD hideHUD];
        
        weakSelf.bottomBtn.userInteractionEnabled = YES;
        
        if (NET_RESULT_CODE == 200) {
            [MBProgressHUD showMessage:@"会员开通成功，请填写公司资料"];
            weakSelf.model.level = 1;
            
            weakSelf.model.openingTime = [NSString stringFromDate:weakSelf.startDate];
            weakSelf.model.expirationTime = [NSString stringFromDate:weakSelf.endDate];
            
            [weakSelf UIConfig];
            
        } else {
            NET_SHOW_MSG;
        }
    } failure:^(NSError * _Nonnull error) {
        [MBProgressHUD hideHUD];
        weakSelf.bottomBtn.userInteractionEnabled = YES;
        NET_SHOW_ERROR;
    }];
}

// 保存公司资料
-(void)saveCompanyNetwork {
    
    if (![self.companyNameTF.text isNotBlank]) {
        [MBProgressHUD showMessage:@"请填写公司名称"];
        return;
    }
    if (![self.companyShortNameTF.text isNotBlank]) {
        [MBProgressHUD showMessage:@"请填写公司简称"];
        return;
    }
    if (![self.companyUserTF.text isNotBlank]) {
        [MBProgressHUD showMessage:@"请填写联系人"];
        return;
    }
    if (![self.companyUserPhoneTF.text isNotBlank]) {
        [MBProgressHUD showMessage:@"请填写联系人电话"];
        return;
    }
    
    NSMutableDictionary *dic = [[NSMutableDictionary alloc]init];
    [dic setObject:self.model.userId forKey:@"userId"];// 用户id
    [dic setObject:self.companyNameTF.text forKey:@"name"];// 公司名称
    [dic setObject:self.companyShortNameTF.text forKey:@"abbName"];// 公司简称
    [dic setObject:self.companyUserTF.text forKey:@"linkman"];// 联系人
    [dic setObject:self.companyUserPhoneTF.text forKey:@"phone"];// 电话
    
    self.bottomBtn.userInteractionEnabled = NO;
    
    WeakSelf;
    [MBProgressHUD showLoadingMessage:nil];
    [[APIManager manager] Post:URL_saveCompanyInfo parameters:dic success:^(id  _Nonnull responseObject) {
        [MBProgressHUD hideHUD];
        if (NET_RESULT_CODE == 200) {
            [MBProgressHUD showMessage:@"资料保存成功"];
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                [weakSelf.navigationController popViewControllerAnimated:YES];
            });
        } else {
            NET_SHOW_MSG;
            weakSelf.bottomBtn.userInteractionEnabled = YES;
        }
    } failure:^(NSError * _Nonnull error) {
        weakSelf.bottomBtn.userInteractionEnabled = YES;
        [MBProgressHUD hideHUD];
        NET_SHOW_ERROR;
    }];
    
}

#pragma mark - Method

-(void)openMemberAction {
    if (!self.startDate) {
        [MBProgressHUD showMessage:@"请选择会员开始时间"];
        return;
    }
    
    if (!self.endDate) {
        [MBProgressHUD showMessage:@"请选择会员结束时间"];
        return;
    }
    
    WeakSelf;
    [UIAlertController alertWithController:self title:[NSString stringWithFormat:@"是否确定为该用户开通%@时长的会员？", [self getRegionTime]] message:nil actionTitles:@[@"取消", @"确定"] actionOne:nil actionTwo:^{
        [weakSelf openMemberNetwork];
    }];
    
}

// 计算间隔时间
-(NSString *)getRegionTime {
    
    NSDateComponents *components = [NSDate compareFromZeroWithDate:self.startDate anotherDate:self.endDate];
    
    NSString *timeStr = @"";
    if (components.year != 0) {
        timeStr = [NSString stringWithFormat:@"%@%ld年", timeStr, components.year];
    }
    if (components.month != 0) {
        timeStr = [NSString stringWithFormat:@"%@%ld月", timeStr, components.month];
    }
    if (components.day != 0) {
        timeStr = [NSString stringWithFormat:@"%@%ld天", timeStr, components.day];
    }
    
    return  timeStr;
}

// 计算剩余时间
-(NSString *)getRemainingTime {
    
    NSDate *endTime = [NSDate dateFromString:self.model.expirationTime];
    
    NSDateComponents *components = [NSDate compareDate:[NSDate date] anotherDate:endTime];
    
    NSString *timeStr = @"";
    if (components.year != 0) {
        timeStr = [NSString stringWithFormat:@"%@%ld年", timeStr, components.year];
    }
    if (components.month != 0) {
        timeStr = [NSString stringWithFormat:@"%@%ld月", timeStr, components.month];
    }
    if (components.day != 0) {
        timeStr = [NSString stringWithFormat:@"%@%ld天", timeStr, components.day];
    }
    if (components.hour != 0) {
        timeStr = [NSString stringWithFormat:@"%@%ld时", timeStr, components.hour];
    }
    if (components.minute != 0) {
        timeStr = [NSString stringWithFormat:@"%@%ld分", timeStr, components.minute];
    }
    
    return  timeStr;
    
}

#pragma mark - Set Get

#pragma mark - Lazy


@end
